/*
 * 
 */
package kds.network.http;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import kds.network.HTTPCachePolicy;

import android.util.Log;

/**
 * The Class URLSycnRequest.
 * 
 * @author h0akd93
 */
public class URLSycnRequest implements Runnable {

	/** The m request url. */
	private String mRequestUrl;

	/** The cache policy. */
	private HTTPCachePolicy cachePolicy = HTTPCachePolicy.NOCACHE;

	/**
	 * Instantiates a new uRL request.
	 * 
	 * @param url
	 *            the url
	 * @param httpURLRequestDelegate
	 *            the http url request delegate
	 */
	public URLSycnRequest(String url) {
		mRequestUrl = url;
	}

	/**
	 * Convert request to string use for dump request
	 */
	public String toString() {
		return "<Request:" + mRequestUrl + ">";
	}

	/**
	 * Send.
	 */
	public void send() {
		URLSyncManager.getSyncQueue().push(this);
	}

	/**
	 * Main runnable of request.From here URLSycnRequest request to server
	 */
	@Override
	public void run() {
		InputStream is = null;
		try {

			URL url = new URL(mRequestUrl);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoInput(true);

			// Starts the query
			conn.connect();

			is = conn.getInputStream();
			HTTPResponseData data = new HTTPResponseData(is);

			HTTPResponseCache.getSharedCache().saveCacheForRequest(mRequestUrl,
					data, cachePolicy);

			conn.disconnect();
			Log.i("URLSycnRequest", "Sync request load finish:" + mRequestUrl);
		} catch (Exception e) {
			Log.e("URLSycnRequest", "Sync request erro:" + mRequestUrl, e);
			URLSyncManager.getSyncQueue().didRequestLoader(this);
		} finally {
		}

	}

	/**
	 * @return
	 */
	public HTTPCachePolicy getCachePolicy() {
		return cachePolicy;
	}

	/**
	 * @param cachePolicy
	 */
	public void setCachePolicy(HTTPCachePolicy cachePolicy) {
		this.cachePolicy = cachePolicy;
	}

}
